package com.beta.cust.bind.datasync.config;

import com.beta.cust.bind.datasync.constant.WxWorkUrlContants;
import com.beta.cust.bind.datasync.utils.SM4Helper2;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@RefreshScope
@Data
@Slf4j
public class CfgSelfRefreshBean implements InitializingBean {

    /**
     * 企业微信域名 生产为qyapi.weixin.qq.com 其余环境qyapi-weixin-qq-com.test.betawm.com
     */
    @Value("${wxwork.domain.name:https://qyapi.weixin.qq.com}")
    private String wxworkDomainName;

    /**
     * 企业agentid 获取方式：应用管理-自建应用-AgentId
     */
    @Value("${crm.task.open:false}")
    private String crmTaskOpen;

    /**
     * 企业agentid 获取方式：应用管理-自建应用-AgentId
     */
    @Value("${agentId:1000003}")
    private String agentId;

    /**
     * 请求企微获取下游企业列表 每页大小
     */
    @Value("${corpLimit:100}")
    private Integer corpLimit;

    /**
     * 企业id 获取方式：我的企业-企业ID
     */
    @Value("${enterpriseId:ww69b508e55f4969f8}")
    private String corpId;

    /**
     * 企业密码 获取方式：应用管理-自建应用-Secret
     */
    @Value("${enterpriseSecret:_wlZzAhOKppWpFWJWunLz7RCVCREaUIEcL6hLZnB03E}")
    private String corpSecret;

    @Value("${sToken:YXsfmNMntG3t8dgSmYe}")
    private String sToken;

    @Value("${sEncodingAESKey:yKBvXaa0EkwI9UEiUxHMiSpXv9c36DrgVtGrcNzwbHC}")
    private String sEncodingAESKey;

    @Value("${emergencyLogin.maxErrorTimes:999}")
    private Integer maxErrorTimes;

    @Value("${iam.auth.check.url:999}")
    private String iamAuthCheckUrl;

    @Value("${cdn.redundancy.minutes:30}")
    private Long cdnRedundancyMinutes;

    @Value("${clean.ift.expiredFiles.directory:999}")
    private List<String> cleanIftExpiredFilesDirectory;

    @Value("${clean.directory:999}")
    private List<String> cleanDirectory;

    @Value("${wecom.data.clear.month:6}")
    private Integer wecomDataClearMonth;

    @Value("${clean.data.transFlow.interval:6}")
    private Integer transFlowClearInterval;

    @Value("${clean.data.transFlow.unit:M}")
    private String transFlowClearUnit;

    @Value("${clean.data.transFlow.interval:3}")
    private Integer operateLogClearInterval;

    @Value("${clean.data.transFlow.unit:Y}")
    private String operateLogClearUnit;

    @Value("${syncProductInfo.pageSize:1}")
    private int syncProductInfoPageSize;

    @Value("${SM4Helper2.sm4-code:scrm001234567890}")
    private String custEncKey;

    @Value("${delete.expired.data.conf:999}")
    private List<String> deleteExpiredDataConf;

    @Value("${fpcs.statpage.export.max:2000}")
    private Integer maxSize;

    @Value("${fpcs.statpage.export.pageSize:500}")
    private Integer pageSize;

    @Value("${statPageExportNum:2000}")
    private int statPageExportNum;

    @Value("${news.jump.url:999}")
    private String newsJumpUrl;

    @Value("${content.jump.url:999}")
    private String contentJumpUrl;

    @Value("${wx.push.save.size:100}")
    private Integer saveSize;

    /**
     * 是否开启代理,Y表示开启  N表示不开启
     */
    @Value("${http.proxy.enable:999}")
    private String proxyEnable;

    /**
     * 代理类型,目前支持http和socket
     */
    @Value("${http.proxy.type:999}")
    private String proxyType;

    /**
     * 代理地址
     */
    @Value("${http.proxy.host:999}")
    private String proxyHost;

    /**
     * 代理端口
     */
    @Value("${http.proxy.port:999}")
    private Integer proxyPort;

    /**
     * 是否启用代理授权,Y表示开启 N表示不开启
     */
    @Value("${http.proxy.authorize:999}")
    private String proxyAuthorize;

    /**
     * 代理的用户名
     */
    @Value("${http.proxy.username:999}")
    private String proxyUsername;

    /**
     * 代理的密码
     */
    @Value("${http.proxy.password:999}")
    private String proxyPassword;


    /**
     * 获取精编资讯的任务执行时间
     * 1：午报,3：收盘,4：晚报
     */
    @Value("${sync.saasNews.Time:1=11:00:00~14:00:00,4=18:30:00~19:30:00,3=15:00:00~16:30:00}")
    private String syncSaasNewsTime;

    private Map<String, TimeRange> saasNewsTimeRange;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化秘钥
        SM4Helper2.init(custEncKey);
        WxWorkUrlContants.init(wxworkDomainName);

        saasNewsTimeRange = new ConcurrentHashMap<>(3);
        if (StringUtils.isNotEmpty(syncSaasNewsTime)) {
            String[] splits = syncSaasNewsTime.split(",");
            // 1=11:00:00~14:00:00
            for (String split : splits) {
                String[] newsTime = split.split("=");
                // 1
                String type = newsTime[0];
                // 11:00:00~14:00:00
                String time = newsTime[1];

                String[] times = time.split("~");
                LocalTime startTime = LocalTime.parse(times[0]);
                LocalTime endTime = LocalTime.parse(times[1]);

                saasNewsTimeRange.put(type, new TimeRange().setStartTime(startTime).setEndTime(endTime));
            }
        }
    }

    /**
     * 将配置的删除过期数据配置内容转成map结构
     *
     * @return
     */
    public Map<String, Integer> getDeleteExpiredDataMap() {
        //将配置的删除过期数据conf转Map，key以服务类中的name为key
        Map<String, Integer> confMap = new HashMap<>();
        deleteExpiredDataConf.stream().forEach(c -> {
            final String[] split = c.trim().split("-");
            if (split.length != 2 || !StringUtils.isNumeric(split[1])) {
                log.error("数据配置有误，非法格式，conf:{}", c);
            } else {
                Integer days = Integer.valueOf(split[1]);
                confMap.put(split[0], days);
            }
        });

        return confMap;
    }
}
